﻿using Sgr;
using System.Security.Authentication;
using System.Security.Claims;

public class DefaultCurrentUser : ICurrentUser
{
    private readonly IHttpContextAccessor _context;

    public DefaultCurrentUser(IHttpContextAccessor context)
    {
        _context = context ?? throw new ArgumentNullException(nameof(context));
    }

    /// <summary>
    /// 判断当前用户是否已认证
    /// </summary>
    public bool IsAuthenticated =>
        _context.HttpContext?.User?.Identity?.IsAuthenticated ?? false;

    /// <summary>
    /// 当前用户标识
    /// </summary>
    public string? Id
    {
        get
        {
            if (!IsAuthenticated)
                return null;

            return _context.HttpContext?.GetValueFromClaim(Constant.CLAIM_USER_ID);
        }
    }

    /// <summary>
    /// 身份令牌的唯一标识符
    /// </summary>
    public string Jti => _context.HttpContext?.GetValueFromClaim("jti") ?? string.Empty;

    /// <summary>
    /// 当前用户所在组织
    /// </summary>
    public string? OrgId => _context.HttpContext?.GetValueFromClaim(Constant.CLAIM_USER_ORGID);

    /// <summary>
    /// 当前用户登录名称
    /// </summary>
    public string LoginName => _context.HttpContext?.GetValueFromClaim(ClaimTypes.NameIdentifier) ?? string.Empty;

    /// <summary>
    /// 当前用户显示名称
    /// </summary>
    public string DisplayName => _context.HttpContext?.GetValueFromClaim(ClaimTypes.Name) ?? _context.HttpContext?.GetValueFromClaim(ClaimTypes.NameIdentifier) ?? string.Empty;

    public long? TenantId
    {
        get
        {
            return 528;
        }
    }

    /// <summary>
    /// 所在设备指纹
    /// </summary>
    public string DeviceFingerprint
    {
        get
        {
            if (_context.HttpContext == null)
                throw new AuthenticationException("无法获取设备信息");

            return $"{_context.HttpContext.GetClientIpAddress()}-{_context.HttpContext.GetDeviceFingerprint()}";
        }
    }
}